package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Weixin_servlet1
 */
@WebServlet("/Weixin_servlet1")
public class Weixin_servlet1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Weixin_servlet1() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.println("Hello World!");
		String signature = request.getParameter("signature");
		String token = this.getInitParameter("token");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		System.out.println(token+"|"+timestamp+"|"+nonce);
		String[] params = new String[]{token,timestamp,nonce};
		Arrays.sort(params);
		String joinStr = "";
		for(int i=0;i<params.length;i++){
			joinStr += params[i];
		}
		if(signature.equals(makesha1(joinStr))){
			response.getWriter().write(echostr);
		}
		response.getWriter().write("helloyhuso");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	public static String makesha1(String password) {
		MessageDigest md;
		try {
			// 生成一个sha1加密计算摘要
			md = MessageDigest.getInstance("sha1"); // 同样可以使用md5
			// 计算md5函数
			md.update(password.getBytes());
			// digest()最后确定返回sha1 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
			// BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
			String pwd = new BigInteger(1, md.digest()).toString(16); //参数也可不用16,可改动,当然结果也不一样了
			return pwd;
		} catch (Exception e) {
			e.printStackTrace();
		}
			return password;
	}
	
	public static void main(String[] args) {
		String sha1Value = makesha1("123abc");
		System.out.println(sha1Value.length());
		System.out.println(sha1Value);
	}
	
}
